<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/11/6
 * Time: 16:56
 */

namespace app\api\controller;


use app\admin\logic\UserAccessory;
use app\admin\model\user\UserExperts;
use app\admin\model\user\UserExpertsCategory;
use app\admin\model\user\UserExpertsDescribe;
use app\admin\model\user\UserExpertsPrice;
use app\admin\model\user\UserExpertsQualification;
use app\admin\model\user\UserExpertsTrain;
use app\common\controller\Api;
use app\common\model\Category;
use fast\Tree;
use think\Request;

class Experts extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }

    /**
     * 获取专家信息
     * */
    public function index()
    {
        $ue = new UserExperts();
        $info = $ue->field('u_age,u_practitioner_year,u_intro,u_card_front,u_card_verso,u_title,u_status,serve_count,u_name,u.nickname,ue.u_address')
            ->alias("ue")
            ->where('u_uid', $this->auth->id)
            ->join("user u","u.id = ue.u_uid")
            ->find();
        if ($info['u_status'] == 0) {
            $this->error('身份待审核');
        } elseif ($info['u_status'] == 2) {
            $this->error('身份被禁用，请联系管理员');
        } elseif ($info['u_status'] == 3) {
            $this->error('审核被拒绝');
        }
        unset($info['u_status']);

        $this->success('成功', $info, 200);
    }

    /**
     *专家基本信息修改
     * */

    public function edit()
    {
        $params = $this->request->param();
        $ue = new UserExperts();
        $uev = new \app\admin\validate\user\UserExperts();
        if ($uev->scene('edit')->check($params)) {
            $data = [
                'u_age' => $params['age'],
                'u_practitioner_year' => $params['practitioner_year'],
                'u_intro' => $params['intro']
            ];
            $ue->where('u_uid', $this->auth->id)
                ->update($data);
            $this->success('编辑成功','',200);
        } else {
            $this->error($uev->getError());
        }
    }

    /**
     * 资格证书
     * */
    public function get_qualification()
    {
        $ueq = new UserExpertsQualification();
        $list = $ueq->field('ua_id,name,id')->where('uid', $this->auth->id)->select();

        if ($list) {

            foreach ($list as $key => $value) {
                $list[$key]['path'] = (new UserAccessory())->getPath($value['ua_id']);
                unset($list[$key]['ua_id']);
            }
            $this->success('成功', $list, 200);

        } else {
            $this->success('成功', [], 200);
        }
    }

    /**
     * 添加资格证书
     * */

    public function add_qualification()
    {

        $params = $this->request->param();
        $ueq = new UserExpertsQualification();
        $ueqv = new \app\admin\validate\user\UserExpertsQualification();

        if ($ueqv->check($params)) {
            $params = [
                'ua_id' => $params['ua_id'],
                'name' => $params['name'],
                'uid' => $this->auth->id
            ];
            if ($ueq->isExist($params)) {
                $this->error('已存在');
            };
            $params['createtime'] = date('Y-m-d H:i:s');
            $params['uid'] = $this->auth->id;
            if ($ueq->save($params)) {
                $this->success('成功');
            } else {
                $this->error('请重新添加');
            };
        } else {
            $this->error($ueqv->getError());
        };
    }

    //删除资格证书
    public function del_qualification()
    {
        $id = $this->request->param('id');
        $ueq = new UserExpertsQualification();
        $relust = $ueq->where(['id' => $id, 'uid' => $this->auth->id])->delete();
        if ($relust) {
            $this->success('删除成功','',200);
        } else {
            $this->error('删除失败');
        }
    }

    //添加培训经历
    public function add_train()
    {
        $params = $this->request->param();
        $uet = new UserExpertsTrain();
        $where = [
            'uid' => $this->auth->id,
            'datetime' => $params['datetime'],
            'detail' => $params['detail'],
        ];

        if ($uet->isExist($where)) {
            $addData = [
                'uid' => $this->auth->id,
                'datetime' => $params['datetime'],
                'detail' => $params['detail'],
                'createtime' => date('Y-m-d H:i:s')
            ];
            $uet->save($addData);
            $this->success('添加成功', '', 200);
        } else {
            $this->error('已存在，请勿重复添加');
        }
    }

    //培训列表
    public function train_list()
    {
        $uet = new UserExpertsTrain();
        $list = $uet->where('uid', $this->auth->id)->field('id,datetime,detail')->select();
        if ($list) {
            $this->success('成功', $list,200);
        } else {
            $this->success('成功', []);
        }
    }

    //删除培训经历
    public function train_del()
    {
        $id = $this->request->param('id');
        $uet = new UserExpertsTrain();
        $result = $uet->where(['id' => $id])->delete();
        if ($result) {
            $this->success('删除成功','',200);
        } else {
            $this->error('删除失败');
        }
    }

    //专家选择分类列表 二维数组

    public function category_list()
    {
        $category = new Category();
        $tree = Tree::instance();
        $uec = new UserExpertsCategory();
        $categorylist = collection($category->field('id,pid,name,type,flag')->order('weigh desc,id desc')->select())->toArray();
        foreach ($categorylist as $key => $value) {
            if ($uec->isExist($value['id'])) {
                $categorylist[$key]['is_check'] = 1;
            } else {
                $categorylist[$key]['is_check'] = 0;
            }
        }
        $tree->init($categorylist);
        $list = $tree->getTreeArray(0);
        $this->success('成功', $list);
    }

    //添加专家分类

    public function category_add()
    {
        $ids = $this->request->param('ids');
        if (strstr($ids, ',')) {
            $idsArr = explode(',', $ids);
        } else {
            $idsArr = [$ids];
        }
        $uec = new UserExpertsCategory();
        $category = new Category();

        if (is_array($idsArr) && count($idsArr) > 0) {
            $uec->where(['uid' => $this->auth->id])->delete();
            foreach ($idsArr as $key => $value) {
                $isExist = $uec->isExist($value);
                if (!$isExist) {
                    $pid = $category->getPid($value);
                    if ($pid) {
                        if ($uec->isExist($pid)) {
                            $arrOne = [
                                'uid' => $this->auth->id,
                                'c_id' => $value,
                                'create_time' => date('Y-m-d H:i:s'),
                                'pid' => $pid
                            ];
                            $uec->insert($arrOne);
                        } else {
                            $arr = [];
                            $arr[] = [
                                'uid' => $this->auth->id,
                                'c_id' => $pid,
                                'create_time' => date('Y-m-d H:i:s'),
                                'pid' => $pid
                            ];
                            $arr[] = [
                                'uid' => $this->auth->id,
                                'c_id' => $value,
                                'create_time' => date('Y-m-d H:i:s'),
                                'pid' => 0
                            ];
                            $uec->insertAll($arr);
                        }

                    } else {
                        $arrOne = [
                            'uid' => $this->auth->id,
                            'c_id' => $value,
                            'create_time' => date('Y-m-d H:i:s'),
                            'pid' => 0
                        ];
                        $uec->insert($arrOne);
                    }
                }
            }
            $this->success('成功', '', 200);
        } else {
            $this->error('请选择分类');
        }
    }


    /**
     *  专家信息编辑
     * */

    public function edit_describe()
    {
        $params = $this->request->param();
        $ued = new UserExpertsDescribe();
        if ($ued->isExist()) {
            $params['updatetime'] = date('Y-m-d H:i:s', time());
            $result = $ued->where(['uid' => $this->auth->id])->update($params);
            if ($result) {
                $this->success('成功');
            } else {
                $this->error('失败');
            }
        } else {
            $params['uid'] = $this->auth->id;
            $params['createtime'] = date('Y-m-d H:i:s', time());
            $params['updatetime'] = date('Y-m-d H:i:s', time());
            $result = $ued->save($params);
            if ($result) {
                $this->success('成功');
            } else {
                $this->error('失败');
            }
        }
    }

    /**
     * 获取专家描述信息
     * */
    public function describe_info()
    {
        $ued = new UserExpertsDescribe();
        $info = $ued->where(['uid' => $this->auth->id])->field('crowd,duration_time,therapy,style')->find();
        if ($info) {
            $info = $info->toArray();
        } else {
            $info = [];
        }
        $this->success('成功', $info,200);
    }

    /**
     * 收费标准设置
     * */

    public function price_set()
    {
        $params = $this->request->param();
        $uep = new UserExpertsPrice();
        if ($uep->isExist()) {
            $result = $uep->where(['uid' => $this->auth->id])->update($params);
            if ($result) {
                $this->success('成功','',200);
            } else {
                $this->error('设置失败');
            }
        } else {
            $params['uid'] = $this->auth->id;
            $result = $uep->save($params);
            if ($result) {
                $this->success('成功','',200);
            } else {
                $this->error('设置失败');
            }
        }
    }

    public function get_experts_price(){
        $uep = new UserExpertsPrice();
        $priceinfo = $uep->where('uid',$this->auth->id)->field('sound_price,video_price')->find();
        $this->success('请求成功',$priceinfo,200);
    }

    /**
     * 专家订单列表
     * */
    public function order_list()
    {
        $status = $this->request->param('status');
        $page = $this->request->param('page', '1');
        $start_limit = ($page * 10) - 10;
        switch ($status){
            case 1:
                $where = [
                    'o.experts_id'=>$this->auth->id,
                    'o.pay_status'=>'1',
                    'o.status'=>['in',[1,2,3]]
                ];
                break;
            case 2:
                $where = [
                    'o.experts_id'=>$this->auth->id,
                    'o.pay_status'=>'1',
                    'o.status'=>['in',[4]]
                ];
                break;
            case 3:
                $this->error('状态错误');
                break;
        }
        $order = new \app\admin\model\order\Order();

        $list = $order
            ->where($where)
            ->alias('o')
            ->join('fa_user u', 'o.uid = u.id')
            ->order('order_id', 'desc')
            ->field('u.nickname,u.avatar,o.order_id,o.createtime,o.type,o.status,o.appoint_time,o.price,o.consult_type')
            ->limit($start_limit,10)
            ->select();
        if ($list) {
            $list = collection($list)->toArray();
            foreach ($list as $key => $value) {
                if ($value['type'] == 1) {
                    $list[$key]['type'] = '音频通话';
                } else {
                    $list[$key]['type'] = '视频通话';
                }
                $list[$key]['status'] = $this->getStatus($value['status']);
            }
        } else {
            $list = [];
        }
        $this->success('成功', $list, 200);
    }

    /**
     * 专家订单详情
     * */
    public function order_detail(){
        $order_id = $this->request->param('order_id');
        $order = new \app\admin\model\order\Order();
        $where = [
            'order_id' => $order_id,
            'experts_id' => $this->auth->id
        ];
        $orderInfo = $order->where($where)->alias('o')
            ->join('fa_user u', 'o.uid = u.id')
            ->order('order_id', 'desc')
            ->field('u.nickname,u.avatar,o.order_id,o.createtime,o.type,o.status,o.appoint_time,o.price,o.consult_type,o.pay_type,o.pay_time,o.order_sn')
            ->find();
        if ($orderInfo) {
            if ($orderInfo['type'] == 1) {
                $orderInfo['type'] = '音频通话';
            } else {
                $orderInfo['type'] = '视频通话';
            }
            $orderInfo['status'] = $this->getStatus($orderInfo['status']);
            $this->success('成功',$orderInfo,200);
        } else {
            $this->success('成功',$orderInfo,200);
        }
    }

    /**
     * 获取状态
     * @param $status 状态
     * */
    public function getStatus($status)
    {
        $s = '';
        switch ($status) {
            case 0:
                $s = '待支付';
                break;
            case 1:
                $s = '已支付';
                break;
            case 2:
                $s = '已约时间';
                break;
            case 3:
                $s = '改约时间';
                break;
            case 4:
                $s = '订单已完成';
                break;
            case 5:
                $s = '未支付 订单取消';
                break;
            case 6:
                $s = '退款';
                break;
            default:
                $s = '状态错误';
        }

        return $s;

    }


}